package com.bosssoft.itfinance.citizen.smsclient.common;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.bosssoft.itfinance.citizen.sms.dubboservice.ISmsDubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 获取dubbo作业任务工厂(包括尝试机制)
 * Created by Zxy on 2017/9/20.
 */
public class DubboFactory {

    private static Logger logger = LoggerFactory.getLogger(DubboFactory.class);
    private static int timeout=30000;
    private static String regUrl="zookeeper://192.168.126.66:2181";
    private static Map<String, ReferenceConfig<ISmsDubboService>> referenceMap = new HashMap<>();

    public static ISmsDubboService getService(String group, String version) {
        String dubboKey = group + version;
        ReferenceConfig<ISmsDubboService> reference = referenceMap.get(dubboKey);
        if (reference == null) {
            reference = addReference(group, version);
        }
        return reference.get();
    }

    private static ReferenceConfig<ISmsDubboService> addReference(String group, String version) {
        ReferenceConfig<ISmsDubboService> reference = new ReferenceConfig<>();
        reference.setApplication(new ApplicationConfig("sms-consumer"));
        reference.setRegistry(new RegistryConfig(regUrl));
        reference.setInterface(ISmsDubboService.class);
        reference.setGroup(group);
        reference.setVersion(version);
        reference.setTimeout(timeout);
        //必须设置为false，不然在第一次获取提供者时，提供者不存在，后期提供者启动后，不能自动获取服务
        reference.setCheck(false);
        referenceMap.put(group + version, reference);
        logger.info("耗资源注意，生成dubbo服务,group={},version={}", group, version);
        return reference;
    }

    private static void sleepWait(int second) {
        try {
            Thread.sleep(second);
        } catch (InterruptedException e) {
            logger.warn("睡眠等待异常", e);
        }
    }

    public static int getTimeout() {
        return timeout;
    }

    public static void setTimeout(int timeout) {
        DubboFactory.timeout = timeout;
    }

    public static String getRegUrl() {
        return regUrl;
    }

    public static void setRegUrl(String regUrl) {
        DubboFactory.regUrl = regUrl;
    }
}
